package com.example.easyexcel.service.impl;

import com.alibaba.excel.EasyExcel;
import com.example.easyexcel.service.EasyExcelService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description :
 * @Author : Bruce Lee
 * @CreateTime : 2024/6/4
 */


@Service
public class EasyExcelServiceImpl implements EasyExcelService {

    @Override
    public void importExcel(MultipartFile file, Class<?> clazz) throws IOException {
        // TODO
    }

    @Override
    public void exportExcel(HttpServletResponse httpServletResponse, List<?> data, Class<?> clazz, String fileName) throws IOException {
        // 将数据用户信息导出成Excel文件并以流的形式返回
        httpServletResponse.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        // 设置字符集
        httpServletResponse.setCharacterEncoding("utf-8");
        // 设置文件名，并且进行编码
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        // 告诉浏览器将以下载的方式处理响应，而不是在浏览器中直接打开(attachment表示下载、filename*=utf-8''" + fileName + ".xlsx"表示下载的文件名)
        httpServletResponse.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(httpServletResponse.getOutputStream(), clazz).sheet("Sheet").doWrite(data);
    }


    @Override
    public void exportExcelTemplate(HttpServletResponse httpServletResponse, Class<?> clazz, String fileName) throws IOException {
        List<Object> list = new ArrayList<>();
        // 将数据用户信息导出成Excel文件并以流的形式返回
        httpServletResponse.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        // 设置字符集
        httpServletResponse.setCharacterEncoding("utf-8");
        // 设置文件名，并且进行编码
        fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        // 告诉浏览器将以下载的方式处理响应，而不是在浏览器中直接打开(attachment表示下载、filename*=utf-8''" + fileName + ".xlsx"表示下载的文件名)
        httpServletResponse.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(httpServletResponse.getOutputStream(), clazz).sheet("Sheet1").doWrite(list);
    }

}
